package com.example.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        HttpSession session = request.getSession();
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();

        // 允许通过的路径
        if (uri.endsWith("index.jsp") ||
                uri.contains("/user/login") ||
                uri.contains("/resources/") ||
                uri.equals(contextPath + "/")) {
            return true;
        }

        // 检查登录状态
        if (session.getAttribute("loggedIn") != null) {
            // 检查用户类型是否匹配访问路径
            String userType = (String) session.getAttribute("userType");

            if (uri.startsWith(contextPath + "/student/") && !"student".equals(userType)) {
                response.sendRedirect(contextPath + "/index.jsp");
                return false;
            }

            if (uri.startsWith(contextPath + "/teacher/") && !"teacher".equals(userType)) {
                response.sendRedirect(contextPath + "/index.jsp");
                return false;
            }

            if (uri.startsWith(contextPath + "/admin/") && !"admin".equals(userType)) {
                response.sendRedirect(contextPath + "/index.jsp");
                return false;
            }

            return true;
        }

        // 未登录重定向到index.jsp
        response.sendRedirect(contextPath + "/index.jsp");
        return false;
    }
}